package org.example.mybatis.plus.boot3.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import org.example.mybatis.plus.boot3.entity.User;
import org.example.mybatis.plus.boot3.service.UserServiceUseMapper;
import org.example.mybatis.plus.boot3.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users/mapper")
public class UserControllerUseMapper {
    @Autowired
    private UserServiceUseMapper userServiceUseMapper;

    @GetMapping
    public List<User> findAll() {
        return userServiceUseMapper.findAll();
    }

    @GetMapping("/{id}")
    public User findById(@PathVariable Long id) {
        return userServiceUseMapper.findById(id);
    }

    @PostMapping
    public String save(@RequestBody User user) {
        int result = userServiceUseMapper.save(user);
        return result > 0 ? "保存成功" : "保存失败";
    }

    @DeleteMapping("/{id}")
    public String delete(@PathVariable Long id) {
        int result = userServiceUseMapper.deleteById(id);
        return result > 0 ? "删除成功" : "删除失败";
    }

    @GetMapping("/page")
    public IPage<UserVo> getUserPage(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "3") int size) {
        return userServiceUseMapper.getUserVoPage(current, size);
    }

    @PutMapping("/version")
    public ResponseEntity<String> updateUser(@RequestBody User user) {
        try {
            boolean success = userServiceUseMapper.updateUser(user);
            if (success) {
                return ResponseEntity.ok("更新成功");
            } else {
                return ResponseEntity.badRequest().body("更新失败，数据可能已被其他用户修改");
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("并发冲突：" + e.getMessage());
        }
    }

}
